const {Builder, By, Key, until} = require('selenium-webdriver');

let currentPage = 1
let maxPage = null

;(async function start() {
  let driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('http://www.lagou.com');
    // 点击深圳
    await driver.findElement(By.css('#changeCityBox ul.clearfix > li:nth-of-type(6)')).click()
    // 搜索前端
    await driver.findElement(By.id('search_input')).sendKeys('前端', Key.RETURN);

    // 当前页数、总页数
    maxPage = await driver.findElement(By.css('.totalNum')).getText()

    // 开启调用代码
    await getData(driver)

  } finally {
    // 退出
    await driver.quit();
  }
})()

// 获取数据的代码
async function getData(driver) {
  currentPage = await driver.findElement(By.css('.curNum')).getText()
  console.log(`当前正在获取第 ${currentPage} 页的数据-------请稍等-------`);
  while(true){
    let flag = true
    try {
      // 找数多条据获取到一个数组
      let items = await driver.findElements(By.css('.item_con_list .con_list_item'))

      // 循环后的数组
      let arr = []

      // 迭代数组，获取所需要的数据
      for (let i = 0; i < items.length; i++) {
        let item = items[i]

        // 获取内容
        let title = await item.findElement(By.css('.p_top h3')).getText()
        let address = await item.findElement(By.css('.p_top .add em')).getText()
        let time = await item.findElement(By.css('.p_top .format-time')).getText()
        let workLink = await item.findElement(By.css('.p_top .position_link')).getAttribute('href')
        let money = await item.findElement(By.css('.money')).getText()
        let background = await item.findElement(By.css('.li_b_l')).getText()
        background = background.replace(money, '')
        let companyName = await item.findElement(By.css('.company .company_name')).getText()
        let companyLink = await item.findElement(By.css('.company .company_name a')).getAttribute('href')
        let companyIndustry = await item.findElement(By.css('.company .industry')).getText()
        let tags = await item.findElement(By.css('.list_item_bot .li_b_l')).getText()
        let welfare = await item.findElement(By.css('.list_item_bot .li_b_r')).getText()

        arr.push({
          title,
          address,
          time,
          workLink,
          money,
          background,
          companyName,
          companyLink,
          companyIndustry,
          tags,
          welfare
        })
      }
      console.log(arr);

      //点击下一页
      if (currentPage <= maxPage) {
        // 点击下一页
        await driver.findElement(By.css('.pager_next')).click()

        await getData(driver)
      }

    } catch (e) {
      if (e) flag = false
    } finally {
      if (flag) break;
    }
  }
}
